package com.kh.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kh.reggie.common.Result;
import com.kh.reggie.entity.Email;
import com.kh.reggie.entity.User;
import com.kh.reggie.mapper.EmailMapper;
import com.kh.reggie.mapper.UserMapper;
import com.kh.reggie.service.UserService;
import com.kh.reggie.utils.EmailUtil;
import com.kh.reggie.utils.VerifyCodeUtil;
import lombok.extern.slf4j.Slf4j;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.Duration;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Random;

import static com.kh.reggie.utils.BaseContext.getCurrentId;
import static java.lang.System.currentTimeMillis;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private EmailUtil emailUtil;
    @Autowired
    private EmailMapper emailMapper;

    @Autowired
    private UserMapper userMapper;
    @Override
    @Transactional
    public Result sendEmail(String email,String code) {
        if (StringUtils.isBlank(email)) {
            throw new RuntimeException("未填写收件人邮箱");
        }

        log.info("传入邮箱为{}", email);

        try {
            Email emailResult = getEmailByEmailId(email);

            LocalDateTime now = LocalDateTime.now();

            long currentMillis = now.toInstant(ZoneOffset.UTC).toEpochMilli();
            long lastCodeTimeMillis = (emailResult != null) ? emailResult.getLastCodeTime().toInstant(ZoneOffset.UTC).toEpochMilli() : 0;

            log.info("当前时间戳: {}", currentMillis);
            log.info("之前时间戳: {}", lastCodeTimeMillis);
            log.info("相差: {}", currentMillis - lastCodeTimeMillis);

            // 检查是否在60秒内
            if (emailResult != null && (currentMillis - lastCodeTimeMillis) < 60000) {
                return Result.error("获取验证码过于频繁，请您稍后再试");
            }

//             如果是新用户，插入记录
            if (emailResult == null) {
                emailResult = new Email();
                emailResult.setEmailId(email);
                try {
                    emailResult.setCode(Integer.valueOf(code));
                } catch (NumberFormatException e) {
                    System.out.println("无效的验证码: " + code);
                    throw new RuntimeException("异常") ; // 结束方法或者抛出异常
                }
                emailResult.setLastCodeTime(now);
                System.out.println("即将插入的 Email 对象: " + emailResult);
//            同步更新User表
//                User user = new User();
//                Random random = new Random();
//                user.setId((10000000 + random.nextLong()% 9000000000L));
//
//                user.setPhone(email);
//                user.setStatus(1);
//                userMapper.insert(user);
                emailMapper.insert(emailResult);


            }
          // 发送验证码邮件
            emailUtil.sendSimpleMail(email, code);
            log.info("验证码发送成功, 验证码为{}", code);

            return Result.success("验证码发送成功,有效期5分钟");
        } catch (Exception e) {
            log.error("验证码发送失败", e);
            return Result.error("验证码发送失败");
        }
    }

    private Email getEmailByEmailId(String email) {
        LambdaQueryWrapper<Email> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Email::getEmailId, email);
        return emailMapper.selectOne(queryWrapper);
    }


    @Override
    public Result login(String email, String code) {
        Email emailResult = getEmailByEmailId(email);

        if (emailResult == null) {
            return Result.error("请重试");
        }
        if(code.equals(emailResult.getCode())){
            LocalDateTime now = LocalDateTime.now();
            long currentMillis = now.toInstant(ZoneOffset.UTC).toEpochMilli();
            long lastCodeTimeMillis = emailResult.getLastCodeTime().toInstant(ZoneOffset.UTC).toEpochMilli();

            log.info("当前时间戳: {}", currentMillis);
            log.info("之前时间戳: {}", lastCodeTimeMillis);
            log.info("相差: {}", currentMillis - lastCodeTimeMillis);

            if (currentMillis - lastCodeTimeMillis > 60000) {
                // 超过60秒验证码过期
                return Result.error("验证码失效，请重试");
            }

            return Result.success("登入成功");
        }
        return Result.error("验证码错误");
    }

}
